//  新建实验器材
<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键字">
                <a-input v-model="queryParam.keywords" placeholder="名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item
                  label="年级"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    v-model="queryParam.grade_id"
                    placeholder="选择年级"
                >
                  <a-select-option :key="option.id" v-for="option in gradeOptions"   :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="5" :sm="24">
              <a-form-item
                  label="学科"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
              >
                <a-select
                    optionFilterProp="title"
                    mode="default"
                    v-model="queryParam.subject_id"
                    placeholder="选择学科"
                >
                  <a-select-option :key="option.id" v-for="option in subjectOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="!advanced && 6 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>

            </span>
            </a-col>

          </a-row>
        </a-form>
      </a-form>

    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
    </div>
    </div>



    <template>
      <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="{ show: true, clear: () => { this.selectedRowKeys = [] } }"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >

        <span slot="status" slot-scope="status,record">
        <a-badge status="success" v-if="status==1" text="显示" />
        <a-badge status="default" v-else text="隐藏" />
      </span>
        <span slot="action" slot-scope="text, record">
        <template >
          <a @click="handleEdit(record)" >编辑</a>
          <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗" @confirm="onDelete(record)"  okText="确定" cancelText="取消">
    <a href="javascript:;">删除</a>
            </a-popconfirm>
        </template>

      </span>
      </s-table>
    </template>

    <a-modal
            title="操作"
            :width="800"
            v-model="visible"
            @ok="handleOk"
    >
      <a-spin :spinning="saveLoading">
        <a-form :form="form">
          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="实验器材名称"
              hasFeedback
          >
            <a-input v-decorator="[
          'name',
          {rules: [{ required: false, message: '请输入班级名称' }]}
        ]"
                     placeholder="请输入实验器材名称"/>
          </a-form-item>

          <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="实验器材简介"
              hasFeedback
          >
            <a-input v-decorator="[
          'desc',
          {rules: [{ required: true, message: '请输入实验器材简介' }]}
        ]"
                     placeholder="请输入实验器材简介"/>
          </a-form-item>

          <a-form-item
                  label="年级"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
          >
            <a-select
                    optionFilterProp="title"
                    v-model="formData.grade_id"
                    placeholder="选择年级"
            >

              <a-select-option :key="option.id" v-for="option in gradeOptions"   :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

<!--          <a-form-item-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--              label="学科"-->
<!--              hasFeedback-->
<!--          >-->
<!--            <a-input v-decorator="[-->
<!--          'subject_id',-->
<!--          {rules: [{ required: true, message: '请输入学科名称' }]}-->
<!--        ]"-->
<!--                     placeholder="请输入学科名称"/>-->
<!--          </a-form-item>-->
          <a-form-item
              label="学科"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <a-select
                optionFilterProp="title"
                mode="default"
                v-model="formData.subject_id"
                placeholder="选择学科"
            >
              <a-select-option :key="option.id" v-for="option in subjectOptions" :title="option.name" :disabled="option.disabled" :value="option.id">{{option.name}}</a-select-option>
            </a-select>
          </a-form-item>

<!-- 器材图片: 参数extra="显示在列表页,推荐尺寸750x750,推荐格式jpg"-->
          <a-form-item
              label="器材图片"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >
            <pic-uploader
                :file-list="formData.pic"
            />
          </a-form-item>

          <a-form-item
              label="视频"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              extra="请上传相关视频"
          >
            <file-uploader
                :file-list="formData.file"
                accept=".mp4,.mov"
            />
          </a-form-item>

          <a-form-item
              label="内容详情"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
          >

            <UEditor  style="width: 400px; height:520px;" :ueditorContent.sync="formData.content" ></UEditor>
          </a-form-item>

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="状态"
                  hasFeedback
          >
            <r-switch  :formData="formData" field="status" :checkedValue="1" :unCheckedValue="2"  checkedChildren="显示" unCheckedChildren="隐藏" />
          </a-form-item>
        </a-form>
      </a-spin>
      <template slot="footer">
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="saveLoading" type="primary" @click="handleOk">保存</a-button>
      </template>
    </a-modal>

  </a-card>
</template>

<script>
  import moment from 'moment'
  import EditableCell from '@/components/EditableCell/'
  import STable from '@/components/table/'
  import {
    materialAdd,
    materialDelete,
    materialEdit,
    materialDetail,
    getExperimentList,
    yearOptions,
    gradeOptions,
    subjectOptions
  } from '@/api/experiment'
  import PicUploader from '@/components/PicUploader/'
  import RSwitch from '@/components/RSwitch/'
  import FileUploader from "@/components/FileUploader/FileUploader/FileUploader"
  import {getUserList} from "@/api/user";
  import UEditor from '@/components/UEditor/'


  export default {
    name: 'SubjectList',
    components: {
      PicUploader,EditableCell,RSwitch,STable, FileUploader,UEditor
    },
    data () {
      return {
        saveLoading:false,
        visible: false,
//        contentription: '全校班级管理。',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
        form: this.$form.createForm(this),
        mdl: {},

        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
          pageNo:1,
        },
        // 表头
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' },
          },
          {
            title: '年级',
            dataIndex: 'grade_name',
            scopedSlots: { customRender: 'grade_name' },
          },
          {
            title: '简介',
            dataIndex: 'desc',
            scopedSlots: { customRender: 'desc' },
          },
          {
            title: '学科',
            dataIndex: 'subject_name',
            scopedSlots: { customRender: 'subject_name' },
          },
          {
            table: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: { customRender: 'action' },
          }
        ],

        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          console.log('loadData');
          console.log(this.queryParam);
          this.queryParam = Object.assign(this.queryParam,parameter);
          return getExperimentList(this.queryParam)
              .then(res => {
                console.log('res');
                return res.data
              })
        },
        list:[

        ],
        subjectOptions:[
        ],
        yearOptions:[
        ],
        gradeOptions:[
        ],
        formData:{
          name:'',
          pic:[],
          file:[],
          id:0,
          rank:0,
          status:1,
          content:'',
        },
        selectedRowKeys: [],
        selectedRows: [],
      }
    },
    created () {
//      getRoleList({ t: new Date()})
    },
    computed:{
    },
    // mounted(){
    //   let that = this;
    //   that.getYearOptions();
    // },

    mounted(){
      let that = this;
      that.getGradeOptions();
      that.getSubjectOptions();
    },

    methods: {
      getSubjectOptions(){
        let that = this;
        subjectOptions()
            .then(res => {
              console.log(res)
              that.subjectOptions =  res.data
            })
      },
      getGradeOptions(){
        let that = this;
        console.log('getGradeOptions1')
        gradeOptions()
            .then(res => {
              console.log(res)
              console.log('getGradeOptions2')
              that.gradeOptions =  res.data
            })
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      handleCancel(){
        this.visible = false
      },
      // 增
      handleAdd() {
        let that = this;
        that.visible = true;
        that.form.resetFields();
        that.formData = {
          name:'',
          pic:[],
          file:[],
          version_id:undefined,
          id:0,
          rank:0,
          status:1,
          content:'',

        }
        setTimeout( () =>{
          that.form.setFieldsValue({ ...that.formData });
        });
      },
      // 改
      handleEdit(record) {
        let self = this
        this.visible = true
//      this.form.resetFields();
        self.form.setFieldsValue({
          name:'',
        });
        this.formData.id = record.id;
        materialDetail({ id: record.id }).then(res => {
          setTimeout(()=>{
            self.form.setFieldsValue({...res.data});
          },1)
          self.formData = {...res.data};
        })
        // console.log(this.mdl)
      },
      // 增改 处理
      handleOk(e) {
        let self = this
        e.preventDefault()
        this.form.validateFields((err, values) => {
          console.log('Received values of form: ', err);
          if (!err) {
            // if(!self.formData.year){
            //   self.$message.error('请选择学年');
            //   return ;
            // }
            console.log('Received values of form: ', values)
            console.log('Received valuess of formData: ', self.formData)
            self.saveLoading = true;
            if(self.formData.id) {
              materialEdit({
                id:self.formData.id,
                status:self.formData.status,
                grade_id:self.formData.grade_id,
                subject_id:self.formData.subject_id,
                desc:values.desc,
                name:values.name,
                pic:self.formData.pic,
                file:self.formData.file,
                content:self.formData.content,
              }).then(res => {
                self.$message.success('修改成功')
                self.$refs.table.refresh(true)
                self.visible = false;
                self.saveLoading = false;
              }).catch(err =>{
                self.$message.error(err.data.msg);
                self.saveLoading = false;
              })
            }else{
              console.log(self.formData)
              materialAdd({
                status:self.formData.status,
                grade_id:self.formData.grade_id,
                subject_id:self.formData.subject_id,
                desc:values.desc,
                name:values.name,
                pic:self.formData.pic,
                file:self.formData.file,
                content:self.formData.content,



              }).then(res => {
                self.$message.success('新增成功')
                self.$refs.table.refresh(true)
                self.visible = false
                self.saveLoading = false;
              }).catch(err =>{
                self.$message.error(err.data.msg);
                self.saveLoading = false;
              })
            }
          }
        })
      },

      // 查
      onSearch() {
        let self = this;
        self.$refs.table.refresh(true)
      },

      // 删
      onDelete(record) {
        let self = this
        materialDelete({ id: record.id  }).then(res => {
          self.$message.success('删除成功')
          self.$refs.table.refresh(true)
        }).catch(err =>{
          self.$message.error(err.data.msg)
        })
      },
    },
    watch: {
      /*
       'selectedRows': function (selectedRows) {
       this.needTotalList = this.needTotalList.map(item => {
       return {
       ...item,
       total: selectedRows.reduce( (sum, val) => {
       return sum + val[item.dataIndex]
       }, 0)
       }
       })
       }
       */
    }
  }
</script>